package cn.foolishbird.crow.core.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * 文件工具类
 *
 * @author foolishbird
 * @date 2022/5/12
 */
public final class LocalFileUtils {

    private static final Logger logger = LoggerFactory.getLogger(LocalFileUtils.class);

    private LocalFileUtils() {

    }

    /**
     * 生成文件
     *
     * @param fileName
     * @return
     */
    public static File createFile(String filePath, String fileName) {
        File file = new File(filePath + File.separator + fileName);

        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                logger.error("创建临时文件失败：{}", e);
                e.printStackTrace();
                throw new RuntimeException("创建临时文件失败");
            }
        }
        return file;
    }

    /**
     * 临时文件
     *
     * @param fileName 源文件名
     * @return 临时文件名
     */
    public static String converterTempFileName(String fileName) {
        String tempFileName = RandomUtils.timeRandomStr(4);
        if (StringUtils.isBlank(fileName)) {
            return tempFileName;
        }
        int index = fileName.lastIndexOf(".");
        if (index < 0) {
            return tempFileName;
        }
        return tempFileName + fileName.substring(index);
    }

}
